package com.example.ctcdemo.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.ctcdemo.annotation.NeedToken;
import com.example.ctcdemo.entity.ResultUtil;
import com.example.ctcdemo.utils.JwtUtil;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @Description /
 * @Auther chongling guo
 * @Date 2021-07-24 10:44
 **/
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从 http 请求头中取出 token
        String token = request.getHeader("token");
        // 如果不是映射到方法直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Method method= handlerMethod.getMethod();

        //检查有没有需要校验Token权限的注解
        if (method.isAnnotationPresent(NeedToken.class)) {
            NeedToken needToken = method.getAnnotation(NeedToken.class);
            if (needToken.required()) {
                response.setContentType("application/json;charset=UTF-8");
                // 执行认证
                if (token == null) {
                    // 没有token
                    String msgJson = JSONObject.toJSONString(ResultUtil.unAuthorized());
                    response.getWriter().println(msgJson);
                    return false;
                }
                // 校验token是否失效或被修改
                try {
                    // token无异常
                    JwtUtil.verify(token);
                    return true;
                } catch (Exception e){
                    // toke异常
                    String msgJson = JSONObject.toJSONString(ResultUtil.tokenError());
                    response.getWriter().println(msgJson);
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
